package com.talent.jiwen_teacher;

import android.app.Activity;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.talent.jiwen_teacher.base.BaseFragment;
import com.talent.jiwen_teacher.course.CourseWaitFragment;
import com.talent.jiwen_teacher.course.WaitSureFragment;
import com.talent.jiwen_teacher.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen_teacher.http.common.ApiFactory;
import com.talent.jiwen_teacher.http.common.HttpUtil;
import com.talent.jiwen_teacher.http.common.ProgressSubscriber;
import com.talent.jiwen_teacher.http.result.OrderListResult;
import com.talent.jiwen_teacher.my.NotificationActivity;
import com.talent.jiwen_teacher.my.WebShowActivity;
import com.talent.jiwen_teacher.util.ImageUtil;
import com.talent.jiwen_teacher.util.MaterialDialogUtil;
import com.talent.jiwen_teacher.util.SPConstant;
import com.talent.jiwen_teacher.util.SPUtil;
import com.talent.jiwen_teacher.util.Validators;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;

import static com.talent.jiwen_teacher.my.WebShowActivity.WEB_INVISIT_TYPE;
import static com.talent.jiwen_teacher.util.Constant.gradeMap;

public class HomeFragment extends BaseFragment {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.noticeLayout)
    RelativeLayout noticeLayout;

    @BindView(R.id.img_no_data)
    ImageView img_no_data;

    @BindView(R.id.redIv)
    ImageView redIv;//信息红点

    @BindView(R.id.invisit_activity)
    ImageView invisit_activity;

    private List<OrderListResult.Order> dataList = new ArrayList<>();

    public static final String REFRESH_HOME_ORDER_LIST = "refresh.home.order.list";
    public static final String RED_GONE = "RED_GONE";

    @Override
    protected void initData() {

        registEventBus();

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(new CommonAdapter<OrderListResult.Order>(getActivity() , R.layout.item_get_order_new , dataList){
            @Override
            protected void convert(ViewHolder holder, final OrderListResult.Order data, final int position) {
                TextView typeTv = holder.getView(R.id.typeTv);
                ImageView txt_test=holder.getView(R.id.txt_test);//试课
                TextView timeTv = holder.getView(R.id.timeTv);
                TextView optionTv = holder.getView(R.id.optionTv);
                TextView gradeTv=holder.getView(R.id.gradeTv);
                optionTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if (data.getAnswerType() == 1){
                            MaterialDialogUtil.getCommonDialog(getActivity(), "提示", "该单为即时单,接单后不能取消"
                                    , "接单", "取消"
                                    , new MaterialDialogUtil.OnDialogPoNeClickListener() {
                                        @Override
                                        public void onPositive() {
                                            getOrder(data.getOrderId() , position);
                                        }

                                        @Override
                                        public void onNegative() {

                                        }
                                    }).show();
                        }else{
                            getOrder(data.getOrderId() , position);
                        }
                    }
                });

                if(data.getOrderType()==1){
                    txt_test.setVisibility(View.VISIBLE);
                }else {
                    txt_test.setVisibility(View.GONE);
                }

                if (data.getAnswerType() == 1){
                    //即时开课
                    typeTv.setBackgroundResource(R.drawable.bg_corner_green_1);
                    typeTv.setText(getString(R.string.immediately));
                    timeTv.setVisibility(View.GONE);
                }else{
                    //预约
                    typeTv.setBackgroundResource(R.drawable.bg_corner_orange_1);
                    typeTv.setText(getString(R.string.order_time));
                    timeTv.setVisibility(View.VISIBLE);
                    timeTv.setTextColor(ContextCompat.getColor(getContext() , R.color.color_FA7D31));
                    SimpleDateFormat df = new SimpleDateFormat("MM月dd日 HH点mm分");
                    timeTv.setText(df.format(new Date(data.getAnswerTime())));
                }

                if(data.getGradeLevel()>0){
                    gradeTv.setText("("+gradeMap.get(data.getGradeLevel())+")");
                }

                ImageView img_head=holder.getView(R.id.img_head);
                ImageUtil.loadCircleImage(getContext() , data.getAskStudentHeadImage() , img_head);
                holder.setText(R.id.contentTv,data.getQuestionIntroduction());

                holder.setText(R.id.nameTv,data.getAskStudentName());

                RecyclerView memberRecyclerView=holder.getView(R.id.memberRecyclerView);
                RecyclerView imgRecyclerView=holder.getView(R.id.imgRecyclerView);
                RelativeLayout rl_bottom=holder.getView(R.id.rl_bottom);
                if(data.getTeachingType()==1){//1v1
                    rl_bottom.setVisibility(View.GONE);
                }else if(data.getTeachingType()==2){//拼班

                    List<OrderListResult.Member> memberList = new ArrayList<>();
                    if (!Validators.isEmpty(data.getMemberList())){
                        memberList.clear();
                        memberList.addAll(data.getMemberList());
                    }
                    if(memberList.size()>0){
                        rl_bottom.setVisibility(View.VISIBLE);
                        holder.setText(R.id.home_count,""+memberList.size());
                        LinearLayoutManager memberLayoutManager = new LinearLayoutManager(getContext());
                        memberLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                        memberRecyclerView.setLayoutManager(memberLayoutManager);
                        memberRecyclerView.setAdapter(new CommonAdapter<OrderListResult.Member>(getContext() , R.layout.item_course_member , memberList){
                            @Override
                            protected void convert(ViewHolder holder, OrderListResult.Member member, int position) {
                                ImageView memberIv = holder.getView(R.id.memberIv);
                                ImageUtil.loadCircleImage(getContext() , member.getStudentHeadImage() , memberIv);
                            }
                        });
                    }else{
                        rl_bottom.setVisibility(View.GONE);
                    }
                }

                if (!Validators.isEmpty(data.getQuestionImages())){
                    imgRecyclerView.setVisibility(View.VISIBLE);
                    final List<String> imgList = new ArrayList<>();
                    String[] imgs = data.getQuestionImages().split(",");
                    for (int i = 0 ; i < imgs.length ; i++){
                        imgList.add(imgs[i]);
                    }
                    LinearLayoutManager imgLayoutManager = new LinearLayoutManager(getContext());
                    imgLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                    imgRecyclerView.setLayoutManager(imgLayoutManager);
                    imgRecyclerView.setAdapter(new CommonAdapter<String>(getContext() , R.layout.item_add_problem_img_new , imgList){
                        @Override
                        protected void convert(ViewHolder holder, String s, final int position) {
                            ImageView imgIv = holder.getView(R.id.imgIv);
                            ImageUtil.loadCorner4Image(getContext() , s , imgIv);
                            imgIv.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    ImageUtil.picturePreviewWithUrl((Activity)getContext(), position  , imgList);

                                }
                            });
                        }
                    });
                }else{
                    imgRecyclerView.setVisibility(View.GONE);
                }
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                getOrderList();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            }
        });

        refreshLayout.autoRefresh();
    }


    public static final String RED_SHOW = "RED_SHOW";

    @Subscribe
    public void onEvent(String flag){
        switch (flag){
            case REFRESH_HOME_ORDER_LIST:
                refreshLayout.autoRefresh();
                break;
            case RED_GONE:
                if(redIv!=null){
                    redIv.setVisibility(View.GONE);
                }
                break;
            case RED_SHOW:
                if(redIv!=null){
                    redIv.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegistEventBus();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_home;
    }

    @OnClick({R.id.noticeLayout,R.id.invisit_activity})
    public void onViewClicked(View view){
        switch (view.getId()){
            case R.id.noticeLayout:
                intentActivity(NotificationActivity.class);
                break;
            case R.id.invisit_activity:
                WebShowActivity.WEB_SHOW_TYPE=WEB_INVISIT_TYPE;
                intentActivity(WebShowActivity.class);
                break;
        }
    }

    /**获取订单列表
     *
     */
    private void getOrderList(){
        Map<String, String> map = new HashMap<>();
        map.put("teacherId" , SPUtil.stringOut(SPConstant.USER_ID));

        Observable observable = ApiFactory.getEducationApiSingleton().getOrderList(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<OrderListResult>(getActivity()) {
            @Override
            protected void _onNext(OrderListResult orderListResult) {
                dataList.clear();
                dataList.addAll(orderListResult.getOrderList());
                recyclerView.getAdapter().notifyDataSetChanged();
                refreshLayout.finishRefresh();
                if(Validators.isEmpty(dataList)){
                    img_no_data.setVisibility(View.VISIBLE);
                }else{
                    img_no_data.setVisibility(View.GONE);
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
                if(refreshLayout!=null){
                    refreshLayout.finishRefresh();
                }
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,false);
    }

    /**抢单
     *
     * @param orderId
     */
    private void getOrder(String orderId ,final int position){
        Map<String, String> map = new HashMap<>();
        map.put("teacherId" , SPUtil.stringOut(SPConstant.USER_ID));
        map.put("orderId" , orderId);

        Observable observable = ApiFactory.getEducationApiSingleton().saveApplyInfo(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<Void>(getActivity()) {
            @Override
            protected void _onNext(Void v) {
                showToast(getString(R.string.apply_order_success));
                dataList.remove(position);
                recyclerView.getAdapter().notifyDataSetChanged();
                if(Validators.isEmpty(dataList)){
                    img_no_data.setVisibility(View.VISIBLE);
                }else{
                    img_no_data.setVisibility(View.GONE);
                }
                EventBus.getDefault().post(CourseWaitFragment.REFRESH_WAIT_COURSE);
                EventBus.getDefault().post(WaitSureFragment.REFRESH_WAIT_SURE);
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,true);
    }
}
